# -*- coding: utf-8 -*-
from . import BaseController
from backend.libs import myjson as json
from backend.models import Operator, Role, RoleOperator
import hashlib


class OperatorListController(BaseController):

    def get(self):
        op = Operator.objects
        operator_name = self.get_argument('operatorName', '')
        if operator_name:
            op = op.filter(username__contains=operator_name)

        status = self.int_argument('status', 0)
        op = op.filter(status=status).order_by('-created_at')
        
        number_per_page = self.int_argument('pageSize', 100)
        paginator = self.pagination(op.all(), number_per_page=number_per_page, m2m_fields=['role_set'])

        return self.render_json(data=paginator)


class CreateOperatorController(BaseController):

    def post(self):
        data = json.loads(self.request.body)
        print(data)
        password = data['password']
        operator_id = data['id']
        if not data['loginname'] or (int(operator_id) <= 0 and not password):
            return self.render_json(code=1001, msg='操作员名称或密码不能为空')

        operator = Operator() if int(operator_id) <= 0 else Operator.objects.filter(id=operator_id).first()
        operator.loginname = data['loginname']
        operator.username = data['username']
        if password:
            # password需要md5
            m2 = hashlib.md5()
            m2.update(password.encode("utf-8"))
            operator.password = m2.hexdigest()
        operator.status = data['status']
        operator.save()

        if int(operator_id) > 0:
            RoleOperator.objects.filter(operator_id=operator_id).all().delete()
            # for r in operator.role_set.all():
            #     r.operators.remove(operator)

        if data.get('checkedRole', []):
            role_id = data.get('checkedRole')[0]
            role = Role.objects.filter(id=role_id).first()
            if role:
                # role.operators.add(operator)
                # role.save()
                rp = RoleOperator()
                rp.role = role
                rp.operator = operator
                rp.save()

        return self.render_json(data=operator.to_dict())


class DeleteoperatorController(BaseController):

    def post(self, operator_id):
        operator_id = int(operator_id)
        if operator_id > 0:
            operator = Operator.objects.filter(id=operator_id).first()
            if operator:
                operator.status = Operator.STATUS_DISABLE
                operator.save()

        return self.render_json()
